package com.ai.dmc.index.core.control;

import java.lang.reflect.Method;
import java.util.Map;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import com.ai.common.xml.util.ControlConstants;
import com.ai.dmc.index.common.exception.ExceptionHandle;
import com.ai.frame.IControlService;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.alibaba.dubbo.config.annotation.Service;

/**
 * 后台服务统一接入
 */
@Service
public class ControlServiceImpl implements IControlService, BeanFactoryAware {
	private static final Logger logger = LoggerFactory
			.getApplicationLog(ControlServiceImpl.class);

	private BeanFactory factory;

	public void setBeanFactory(BeanFactory factory) {
		this.factory = factory;
	}

	public OutputObject execute(InputObject inputObject) {
		OutputObject outputObject = new OutputObject(ControlConstants.RETURN_CODE.IS_OK);
		long start = System.currentTimeMillis();
		try {
			outputObject.setReturnCode(ControlConstants.RETURN_CODE.IS_OK);
			if (inputObject != null) {
				logger.info("INVOKE START!", "service=" + inputObject.getService() + ", method=" + inputObject.getMethod());
				Object object = factory.getBean(inputObject.getService());
				Method mth = object.getClass().getMethod(inputObject.getMethod(), InputObject.class, OutputObject.class);
				mth.invoke(object, inputObject ,outputObject);
				logger.info("INVOKE SECCESS!", "COST="+(System.currentTimeMillis() - start)+"ms");
			} else {
				throw new Exception("InputObject can't be null !!!");
			}
		}catch (Exception e) {
			Map<String,String> map = ExceptionHandle.getExceptionMsgMap(e);
			// 异常处理
			outputObject.setReturnCode(map.get("resultCode"));
			outputObject.setReturnMessage(map.get("resultMsg"));
		} finally{
			//saveUserOperLog(start, System.currentTimeMillis(), inObj, outObj);
		}
		return outputObject;
	}

}
